package netWork;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//Udp服务器
public class UdpEchoServer {
    private DatagramSocket socket = null;

    //构造方法，给socket一个指定端口号
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");

        //一次循环只能处理一条Udp数据报
        while(true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);//接受Udp数据报
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            //requestPacket.getLength()表示实际接受的数据长度
            String response =  process(request);//经过服务器处理的数据
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length
                    ,requestPacket.getSocketAddress());//这里需要传给返回的数据报的地址，所以和接收的数据报创建时不同
            socket.send(responsePacket);//发送Udp数据报

            //打印日志
            System.out.printf("[%s:%d], req:%s resp:%s\n",requestPacket.getSocketAddress().toString(),socket.getPort(),
                    request,response);
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
